<?php

include('loaddb.php');

include('functions.inc.php');
include('searchtranslate.inc.php');

/**
Given a dictionary of the search information, with elements [query, queryjoin, pred, scope]
Returns a dictionary [query, queryjoin, pred, scope] that doesn't have empty query elements
*/
function pruneAwesomeSearch($queryinfo)
{
	$numterms=count($queryinfo['query']);
	// trim out any empty fields
	for ($curterm=0; $curterm<$numterms; $curterm++)
	{
		if (strlen($queryinfo['query'][$curterm])>0)
		{
			$query[]=$queryinfo['query'][$curterm];
			$queryjoin[]=$queryinfo['queryjoin'][$curterm];
			$pred[]=$queryinfo['pred'][$curterm];
			$scope[]=$queryinfo['scope'][$curterm];
		}
	}
	$ret['query']=$query;
	$ret['queryjoin']=$queryjoin;
	$ret['pred']=$pred;
	$ret['scope']=$scope;
	return $ret;
}

/**
Given a mysql connection and dictionary of the search information, with elements [query, queryjoin, pred, scope]
Returns a MySQL query that incorporates the search
*/
function queryAwesomeSearch($mysql,$queryinfo)
{
	// figure out the query to use in the mysql
	$numterms=count($queryinfo['query']);
	$query='';
	$oring=false;
	for ($curterm=0; $curterm<$numterms; $curterm++)
	{
		if ($curterm<$numterms-1)		// do any OR stuff before the main term
		{
			$nextjoin = $queryinfo['queryjoin'][$curterm];
			// might have special OR instructions
			if (!$oring && $nextjoin=="or")
			{
				$query.="(";		// this term is joined by an OR to the next
				$oring=true;
			}
			
		}
		$curphrase = $mysql->escape_string($queryinfo['query'][$curterm]);
		
		// figure out the like part of the where phrase
		$curpred = $queryinfo['pred'][$curterm];
		//print "curpred: $curpred \n";
		switch ($curpred)
		{
			case "contains":
				$wherepred=" like \"%$curphrase%\" ";
				break;
			case "notcontains":
				$wherepred=" not like \"%$curphrase%\" ";
				break;
			case "starts":
				$wherepred=" like \"$curphrase%\" ";
				break;
			case "ends":
				$wherepred=" like \"%$curphrase\" ";
				break;
			case "default":
				$wherepred=" like \"\"";
		}
		
		// figure out the where phrase
		$curscope = $queryinfo['scope'][$curterm];
		switch ($curscope)
		{
			case "file":
				$query.=" filename ".$wherepred;
				break;
			case "folder":
				$query.=" pathname ".$wherepred;
				break;
			case "folderfile":
			default:
				$query.=" (pathname ".$wherepred." or filename ".$wherepred.") ";
				break;
		}
		
		// add in the joiners
		if ($curterm<$numterms-1)		// do any OR stuff before the main term
		{
			$nextjoin = $queryinfo['queryjoin'][$curterm];
			// might have special OR instructions
			if ($oring && $nextjoin=="and")
			{
				$query.=")";		// this term is the end of a group of ORs
				$oring=false;
			}
			if ($nextjoin=="or")
			{
				$query.=" or ";		// this term is joined by an OR to the next
			}
			if ($nextjoin=="and")
			{
				$query.=" and ";	// this term is joined by an AND to the next
			}
		}
		else
		{
			if ($oring)
			{
				$query.=")";
			}
		}
	}
	return $query;
}

/**
Given a dictionary of the search information, with elements [query, queryjoin, pred, scope]
Returns a string that describes the search
*/
function prettyAwesomeSearch($queryinfo)
{
	// figure out what the pretty query should be
	$numterms=count($queryinfo['query']);
	$contains=Array();
	$notcontains=Array();
	$starts=Array();
	$ends=Array();
	for ($curterm=0; $curterm<$numterms; $curterm++)
	{
		$curquery=$queryinfo['query'][$curterm];
		$curpred=$queryinfo['pred'][$curterm];
		switch ($curpred)
		{
			case "contains":
				$contains[]=$curquery;
				break;
			case "notcontains":
				$notcontains[]=$curquery;
				break;
			case "starts":
				$starts[]=$curquery;
				break;
			case "ends":
				$ends[]=$curquery;
				break;
			default:
				$contains[]=$curquery;
		}
	}
	$prettyquerys=Array();
	if (count($contains))
		$prettyquerys[]="Contains ".implode(', ',$contains);
	if (count($notcontains))
		$prettyquerys[]="Doesn't contain ".implode(', ',$notcontains);
	if (count($starts))
		$prettyquerys[]="Starts with ".implode(', ',$starts);
	if (count($ends))
		$prettyquerys[]="Ends with ".implode(', ',$ends);
	$prettyquery=implode('. ',$prettyquerys);
	//print "Pretty query: $prettyquery";
	return $prettyquery;
}

/**
Given a mysql connection and a dictionary of search information stuff
Returns a list of [query to be used by MySQL, pretty query to display]
*/
function queryOldSearch($mysql,$queryinfo)
{
	if ($_GET['searchtype']=='keywordsOR' || $_GET['searchtype']=='keywordsAND')
	{
		$phrase=$mysql->escape_string(trim($_GET['query']));
		$keywords=split("[\n\r\t ]+", $phrase);
		foreach ($keywords as $keyword)
		{
			$querys[]="(pathfile like '%$keyword%')";
		}
		if ($_GET['searchtype']=='keywordsAND')
		{
			$query=implode(' and ',$querys);
			$prettyquery="Contains all terms: ".$_GET['query'];
		}
		if ($_GET['searchtype']=='keywordsOR')
		{
			$query=implode(' or ',$querys);
			$prettyquery="Contains any term: ".$_GET['query'];
		}
		$filetype=$mysql->escape_string($_GET['filetype']);
		$showbyip=isset($_GET['byip']);

	}
	else
	{
		$phrase=$mysql->escape_string('%'.$_GET['query'].'%');
		$query="(pathfile like '$phrase')";
		$filetype=$_GET['filetype'];
		$prettyquery="Contains exact phrase \"".$_GET['query']."\"";
		$showbyip=isset($_GET['byip']);
	}
	$ret[0]=$query;
	$ret[1]=$prettyquery;
	return $ret;
}

function generateLink($searchid, $pagenumber=-1, $sort="", $extracolumns="")
{
	$script=$_SERVER['PHP_SELF'];
	$link="$script?searchid=$searchid";
	if ($pagenumber==-1)
		$pagenumber=isset($_GET['page']) ? $_GET['page']+0 : -1;
	if ($pagenumber>0)
		$link="$link&amp;page=$pagenumber";
	if ($sort!="")
		$link="$link&amp;sort=$sort";
	if ($sort=="" && isset($_GET['sort']))
		$link="$link&amp;sort=$_GET[sort]";
	if (isset($_GET['byip']))
		$link="$link&amp;byip=true";
		
	if (isset($_GET['extracolumns']) && $extracolumns!='')
		$link="$link&amp;extracolumns=$_GET[extracolumns],$extracolumns";
	if (isset($_GET['extracolumns']) && $extracolumns=='')
		$link="$link&amp;extracolumns=$_GET[extracolumns]";
	if (!isset($_GET['extracolumns']) && $extracolumns!='')
		$link="$link&amp;extracolumns=$extracolumns";
	
	return $link;
}

function showNavBar($id="navigation")
{
	global $numresults;
	global $pagenumber;
	global $count;
	global $searchid;

	$script=$_SERVER['PHP_SELF'];

	$maxpage=floor($numresults/$count);
	$prevpage=max(0,$pagenumber-1);
	$prevpage=min($maxpage,$prevpage);	// if beyond the end of the list, have a previous to go to the last page
	$nextpage=min($maxpage,$pagenumber+1);

	$link=generateLink($searchid, $prevpage);
	print "<div id=\"$id\">\n";
	if ($prevpage<$pagenumber)
		print "<a href=\"$link\">Previous</a>\n";
	else
		print "Previous\n";

	$link=generateLink($searchid, $nextpage);
	if ($nextpage>$pagenumber)
		print "<a href=\"$link\">Next</a>\n";
	else
		print "Next\n";
	print "</div>\n";
}

// Find current scan
$result=$mysql->query("select value from int_settings where name='curscan'");
if ($result->num_rows==0)
	exit;
$myrow=$result->fetch_array();
$curscan=$myrow[0];	

$numresults=0;

if ((isset($_GET['query']) && isset($_GET['filetype'])) 
	|| isset($_POST['awesomesearch'])
	|| isset($_POST['naturalsearch']))
{	

	// process awesome new search
	if (isset($_POST['awesomesearch']))
	{
		$queryinfo=pruneAwesomeSearch($_POST);
		$where=queryAwesomeSearch($mysql,$queryinfo);
		$prettyquery=prettyAwesomeSearch($queryinfo);
		$filetype=$_POST['filetype'];
		$searchopts=array('where'=>$where, 'relevancy'=>'null');
	}
	else if (isset($_POST['naturalsearch']))	// process natural search
	{
		$search=$mysql->escape_string($_POST['query']);
		$where="match (pathname,filename) against ('$search')";
		$prettyquery="Matches \"".$_POST['query']."\"";
		$filetype=$_POST['filetype'];
		$searchopts=array( 'where' => "match (pathfile) against ('$search')", 'relevancy' => "match (pathfile) against ('$search')");
	}
	else	// process old search
	{
		$returned=queryOldSearch($mysql,$_POST);
		$where=$returned[0];
		$prettyquery=$returned[1];
		$filetype=$_GET['filetype'];
		$searchopts=array('where'=>$where, 'relevancy'=>'null');
	}
	$storagedquery=$mysql->escape_string($where);
	$storagedpretty=$mysql->escape_string($prettyquery);
	$offline=isset($_REQUEST['offline'])?'1':'0';
	$result=$mysql->query("select id,prettyquery,filetype,numresults from searches where scanid='$curscan' and query='$storagedquery' and numresults is not null and filetype='$filetype' and offline='$offline'");
	if ($result->num_rows==0)
	{
		$mysql->query("create temporary table temp_searchresults (fileid bigint unsigned, relevancy smallint)");
		if (!isset($_REQUEST['offline']))		// if they have not checked "include offline files", include a count of only online files
			$mysql->query("insert into searches (scanid,query,prettyquery,filetype,offline,numsearched,started) select '$curscan','$storagedquery','$storagedpretty','$filetype', 0, count(*), now() from file_stats where scanid=$curscan");
		else
			$mysql->query("insert into searches (scanid,query,prettyquery,filetype,offline,numsearched,started) select '$curscan','$storagedquery','$storagedpretty','$filetype', 1, count(*), now() from files");
		$searchid=$mysql->insert_id;
		
		$starttime=microtime(true);
		$queries=array();

		$where=$searchopts['where'];
		$relevancy=$searchopts['relevancy'];
			
		if (!isset($_REQUEST['offline']))		// if they have not checked "include offline files", search only files that are online at the current scan
			$filestats="join file_stats on (files.id=file_stats.fileid and file_stats.scanid=$curscan)";
		else
			$filestats='';
				
		if (strlen($filetype)>0)
		{
			$query="select files.id,($relevancy*500) as relevancy from files 
				join hosts on (files.hostid = hosts.id)
				join paths on (files.pathid = paths.id)
				$filestats
				join extensiontypes on (files.extensionid=extensiontypes.extensionid)
				where $where
				and extensiontypes.extensiontype='$filetype'
				order by null";
		}
		else
		{
			$query="select files.id,($relevancy*500) as relevancy from files 
				join hosts on (files.hostid = hosts.id)
				join paths on (files.pathid = paths.id)
				$filestats
				where $where
				order by null";
		}
		$result=$mysql->query("insert ignore into temp_searchresults $query" );
		$time=round((microtime(true)-$starttime)*1000);
#		echo("Took ".$time." to conduct the search<br \>");
		$numrows=$mysql->affected_rows;
#		echo("Found ".$numrows." rows<br />");

		$starttime2=microtime(true);
		$result=$mysql->query("insert ignore into searchresults (select $searchid,fileid,relevancy from temp_searchresults)" );
		$time2=round((microtime(true)-$starttime2)*1000);
#		echo("Took ".$time2." to copy the results<br \>");
		$totaltime=round((microtime(true)-$starttime)*1000);

		$starttime3=microtime(true);
		$mysql->query("update searches set numresults=$numrows, time=$totaltime where id='$searchid'");
		$time3=round((microtime(true)-$starttime3)*1000);
#		echo("Took ".$time3." to update the search<br \>");
		$mysql->query("insert into searchtimes (`searchid`, `temp`, `copy`, `update`) values ($searchid, $time, $time2, $time3)");
	}
	else
	{
#		echo("Found old search<br />");
		$myrow=$result->fetch_array();
		$searchid=$myrow[0];
	}
	$fullpath=dirname($_SERVER['SCRIPT_NAME']).'/search.php?searchid='.$searchid;
	header("Location: $fullpath");
	echo "Your search is complete. <a href=\"$fullpath\">Click to continue</a>";
	
}
else if (isset($_GET['searchid']))
{
	// Figure out the Limit phrase
	$pagenumber=isset($_GET['page']) ? $_GET['page']+0 : 0;
	$pagenumber=max(0,$pagenumber);
	$count=100;
	$start=$pagenumber*$count;
	$limit=" limit $start,$count";
	
	$searchid=$_GET['searchid']+0;
	
	$result=$mysql->query("select prettyquery,filetype,offline,numresults,numsearched,time from searches where id=$searchid");
	$myrow=$result->fetch_array();
	$prettyquery=$myrow[0];
	$filetype=$myrow[1];
	$offline=$myrow[2] ? ', including offline files,' : '';
	$numresults=$myrow[3];
	$numresultsoutput=number_format($myrow[3]);
	$numsearched=number_format($myrow[4]);
	$searchtime=number_format($myrow[5]/1000,3);

	$extracolumns=array("added_date"=>"Added Date", "modified_date"=>"Modified Date");

	if (!isset($_GET['sort']))
		$order="relevancy DESC, hosts.hostname, paths.pathname, files.filename";
	else
	{
		if ($_GET['sort']=='filesizeASC')
			$order="filesize ASC, relevancy DESC, hosts.hostname, paths.pathname, files.filename";
		if ($_GET['sort']=='filesizeDESC')
			$order="filesize DESC, relevancy DESC, hosts.hostname, paths.pathname, files.filename";
		if ($_GET['sort']=='hostASC')
			$order="hosts.hostname ASC, relevancy DESC, paths.pathname, files.filename";
		if ($_GET['sort']=='hostDESC')
			$order="hosts.hostname DESC, relevancy DESC, paths.pathname, files.filename";
		if ($_GET['sort']=='added_dateASC')
			$order="added_date DESC, relevancy DESC, hosts.hostname, paths.pathname, files.filename";
		if ($_GET['sort']=='added_dateDESC')
			$order="added_date ASC, relevancy DESC, hosts.hostname, paths.pathname, files.filename";
		if ($_GET['sort']=='modified_dateASC')
			$order="modified_date DESC, relevancy DESC, hosts.hostname, paths.pathname, files.filename";
		if ($_GET['sort']=='modified_dateDESC')
			$order="modified_date ASC, relevancy DESC, hosts.hostname, paths.pathname, files.filename";
	}

	$extracolfields='';
	$extracoljoins='';
	if (isset($_GET['extracolumns']))
	{
		$extracols=explode(',',$_GET['extracolumns']);
		if (in_array('added_date',$extracols))
		{
			$extracolfields.=', added_date';
			$extracoljoins.='';
		}
		if (in_array('modified_date',$extracols))
		{
			$extracolfields.=', modified_date';
			$extracoljoins.=' JOIN file_stats_single ON (files.id = file_stats_single.fileid)';
		}
	}
		
	
	$sql="SELECT INET_NTOA(host_stats.ip) as ip, hosts.protocol, hosts.hostname, paths.fullpathname as pathname, files.filename, file_stats.filesize $extracolfields FROM searchresults
		JOIN files on (searchresults.fileid = files.id)
		JOIN hosts on (files.hostid = hosts.id)
		JOIN paths on (files.pathid = paths.id)
		JOIN file_stats on (files.id = file_stats.fileid AND files.lastscan = file_stats.scanid)
		JOIN host_stats on (hosts.id = host_stats.hostid AND hosts.lastscan = host_stats.scanid)
		$extracoljoins
		WHERE searchresults.searchid = $searchid
		order by $order
		$limit";
	$result=$mysql->query($sql);
	
	$pagetitle="Search Results";
	include('header.php');

	showCrumbs('searchresults');

	print "<p>Showing results for your search: ".htmlspecialchars($prettyquery)."</p>\n";
	print "<p>Found $numresultsoutput results out of $numsearched searched files$offline in $searchtime seconds</p>\n";
	if ($result->num_rows>0)
	{
		$link=generateLink($searchid);
			
		if (!isset($_GET['byip']))
		{
			print "<div>URLs don't work? Try <a href=\"$link&amp;byip=true\">browsing by IP</a></div>\n";
		}
		print "<div id=\"searchresults\"> \n";
		showNavBar("navigationTop");
	
		print "<table>\n";
		print " <thead>\n";
		print " <tr>\n";
		
		// filesize header
		$newsort="filesize";
		$asc="DESC";
		if (isset($_GET['sort']) && $_GET['sort']=="$newsort$asc")
			$asc="ASC";
		$link=generateLink($searchid, $pagenumber, $newsort.$asc);
		print "  <td><a href=\"$link\">Filesize</a></td>\n";
		
		// extra columns
		if (isset($extracols))
		{
			if (in_array('added_date',$extracols))
			{
				$newsort='added_date';
				$asc='DESC';
				if (isset($_GET['sort']) && $_GET['sort']=="$newsort$asc")
					$asc='ASC';
				$link=generateLink($searchid, -1, $newsort.$asc);
				print "  <td><a href=\"$link\">$extracolumns[$newsort]</a></td>\n";
			}
			if (in_array('modified_date',$extracols))
			{
				$newsort='modified_date';
				$asc='DESC';
				if (isset($_GET['sort']) && $_GET['sort']=="$newsort$asc")
					$asc='ASC';
				$link=generateLink($searchid, -1, $newsort.$asc);
				print "  <td><a href=\"$link\">$extracolumns[$newsort]</a></td>\n";
			}
		}
		
		// host header
		$newsort="host";
		$asc="ASC";
		if (isset($_GET['sort']) && $_GET['sort']=="$newsort$asc")
			$asc="DESC";
		$link=generateLink($searchid, $pagenumber, $newsort.$asc);
		print "  <td><a href=\"$link\">Server</a> Path &nbsp;&nbsp;\n";
		
		$remainingextracolumns=array();
		$selectedextracolumns=explode(',', $_GET['extracolumns']);
		foreach ($extracolumns as $extracolumn=>$text)
			if (!in_array($extracolumn, $selectedextracolumns))
				$remainingextracolumns[$extracolumn]=$text;
		if (count($remainingextracolumns)>0)
		{
			print "   <ul id=\"extracolumnslist\">\n";
			print "    <li>&nbsp;+&nbsp;\n";
			print "     <ul>\n";
			foreach ($remainingextracolumns as $extracolumn=>$text)
			{
				$link=generateLink($searchid, -1, '', $extracolumn);
				print "      <li><a href=\"$link\">$text</a></li>\n";
			}
			print "     </ul>\n";
			print "    </li>\n";
			print "   </ul>\n";
		}
		print "  </td>\n";
		print " </tr>\n";
		print " </thead>\n";
		print " <tbody>\n";
		while ($myrow=$result->fetch_array())
		{
			print " <tr>\n";
			if (isset($_GET['byip']))
				$host=$myrow['ip'];
			else
				$host=$myrow['hostname'];
			$protocol=$myrow['protocol'];
			$pathname=$myrow['pathname'];
			$filename=$myrow['filename'];
			$filesize=size_readable($myrow['filesize']);
			$url="$protocol://$host/$pathname/$filename";
			$path=urlTranslate($url);

			print "  <td align=\"right\">$filesize</td>\n";

			// extra columns
			if (isset($extracols))
			{
				if (in_array('added_date',$extracols))
				{
					if (!is_null($myrow['added_date']))
						print "  <td>$myrow[added_date]</td>\n";
					else
						print "  <td></td>\n";
				}
				if (in_array('modified_date',$extracols))
				{
					if (!is_null($myrow['modified_date']))
						print "  <td>$myrow[modified_date]</td>\n";
					else
						print "  <td></td>\n";
				}
			}
		

			print "  <td>$path</td>\n";
			print " </tr>\n";
		}
		print "</table>\n";
		showNavBar("navigationBottom");
		print "</div>\n";
	}
	else
	{
		print "No files found\n";
	}

	include("footer.php");
	if (!isset($_GET['page']))
		hitPageCounter($mysql,"search",$prettyquery." ".$filetype);
}
else
{
	$extrahead="<script type=\"text/javascript\" src=\"search.js\"></script>\n";
	$extrahead.="<link rel=\"search\" type=\"application/opensearchdescription+xml\" title=\"Sambaindex\" href=\"sambaindex.xml\" />";
	$pagetitle="Search";
	include('header.php');

	$result=$mysql->query("select distinct(extensiontype) from extensiontypes");
	
	showCrumbs('search');
	print "<p id=\"addsearchprovider\" style=\"display:none\"><a onclick=\"addOpenSearch(); return false\" href=\"http://mycroft.mozdev.org/jsreq.html\">Add Search Plugin</a></p>\n";
	print "<div id=\"searchtypes\">\n";
	print " <div id=\"naturalsearch\">\n";
	print "  <form method=\"post\" action=\"".$_SERVER['PHP_SELF']."\" id=\"naturalsearchform\">\n";
	print "   <div>\n";
	print "    <label>Natural search</label>\n";
	print "    <input type=\"text\" name=\"query\" />\n";
	print "   </div>\n";
	print "   <div>\n";
	print "    <label for=\"natural_filetype\">File type</label>";
	print "    <select name=\"filetype\" id=\"natural_filetype\">\n";
	print "     <option value=\"\">Any</option>\n";
	while ($myrow=$result->fetch_array())
	{
		$filetype=$myrow[0];
		print "    <option value=\"$filetype\">$filetype</option>\n";
	}
	print "    </select>\n";
	print "    <label for=\"natural_offline\">Include offline files</label>\n";
	print "    <input id=\"natural_offline\" type=\"checkbox\" name=\"offline\" />\n";
	print "    <input type=\"submit\" name=\"naturalsearch\" value=\"Search\" />\n";
	print "   </div>\n";
	print "  </form>\n";
	print " </div>\n";
	
	
	print " <div id=\"simplesearch\">\n";
	print "  <form method=\"get\" action=\"".$_SERVER['PHP_SELF']."\" id=\"simplesearchform\">\n";
	print "   <div>\n";
	print "    <label>Standard search</label>\n";
	print "    <select name=\"searchtype\" >\n";
	print "     <option value=\"phrase\">Search for exact phrase</option>\n";
	print "     <option value=\"keywordsAND\">Search for all terms</option>\n";
	print "     <option value=\"keywordsOR\">Search for any terms</option>\n";
	print "    </select>\n";
	print "    <input type=\"text\" name=\"query\" />\n";
	print "   </div>\n";
	print "   <div>\n";
	print "    <label for=\"simple_filetype\">File type</label>";
	print "    <select name=\"filetype\" id=\"simple_filetype\">\n";
	print "     <option value=\"\">Any</option>\n";
	$result->data_seek(0);
	while ($myrow=$result->fetch_array())
	{
		$filetype=$myrow[0];
		print "     <option value=\"$filetype\">$filetype</option>\n";
	}
	print "    </select>\n";
	print "    <label for=\"simple_offline\">Include offline files</label>\n";
	print "    <input id=\"simple_offline\" type=\"checkbox\" name=\"offline\" />\n";
	print "    <input type=\"submit\" value=\"Search\" />\n";
	print "   </div>\n";
	print "  </form>\n";
	print " </div>\n";
	
	// print out new awesome form
	print " <div id=\"awesomeform\" style=\"display:none\">\n";
	print "  <form method=\"post\" action=\"".$_SERVER['PHP_SELF']."\" id=\"awesomesearchform\">\n";
	print "   <div>\n";
	print "    <label>Awesome search</label>\n";
	print "    <div id=\"awesome_terms\"></div>\n";
	print "   </div>\n";
	print "   <div>\n";
	print "    <label for=\"awesome_filetype\">File type</label>\n";
	print "    <select name=\"filetype\" id=\"awesome_filetype\">\n";
	print "     <option value=\"\">Any</option>\n";
	$result->data_seek(0);
	while ($myrow=$result->fetch_array())
	{
		$filetype=$myrow[0];
		print "     <option value=\"$filetype\">$filetype</option>\n";
	}
	print "    </select>\n";
	print "    <label for=\"awesome_offline\">Include offline files</label>\n";
	print "    <input id=\"awesome_offline\" type=\"checkbox\" name=\"offline\" />\n";
	print "    <input type=\"submit\" value=\"Search\" name=\"awesomesearch\" />\n";
	print "   </div>\n";
	print "  </form>\n";
	print " </div>\n";	// awesomeform div

	print "<img style=\"display:none\" src=\"throbber.gif\" id=\"throbber\" alt=\"Search In Progress\" />\n";
	
	print "</div>\n";	// searchtypes div
	
	// Recent searches
	print "<div id=\"recentsearches\">\n";
	print "Recent searches: <br />\n";
	$result=$mysql->query("SELECT searches.id,prettyquery,filetype,offline,numresults FROM `searches` where scanid='$curscan' and numresults is not null order by started desc");
	while ($myrow=$result->fetch_array())
	{
		$searchid=$myrow[0];
		$query=$myrow[1];
		$type=$myrow[2];
		$offline=$myrow[3] ? 'including offline files' : '';
		$numresults=number_format($myrow[4]);
		print "<a href=\"?searchid=$searchid\">$query</a> $type $offline &nbsp;&nbsp;&nbsp; ($numresults results)<br />\n";
	}
	print "</div>\n";

	// Past searches
	print "<div id=\"pastsearches\">\n";
	print "Past searches: <br />\n";
	$result=$mysql->query("SELECT searches.id,prettyquery,filetype,offline,numresults FROM searches where scanid!='$curscan' and numresults is not null order by started desc limit 20");
	while ($myrow=$result->fetch_array())
	{
		$searchid=$myrow[0];
		$query=$myrow[1];
		$type=$myrow[2];
		$offline=$myrow[3] ? 'including offline files' : '';
		$numresults=number_format($myrow[4]);
		print "<a href=\"?searchid=$searchid\">$query</a> $type $offline &nbsp;&nbsp;&nbsp; ($numresults results)<br />\n";
	}
	print "</div>\n";	

	include("footer.php");
	hitPageCounter($mysql,"search");
}
